package com.ky.manage.activity.indoor;

import android.content.Intent;
import android.util.Log;

import com.ky.manage.R;
import com.ky.manage.base.BaseActivity;
import com.ky.manage.constant.OverallData;
import com.ky.manage.model.response.UploadFileInfoResp;
import com.ky.manage.permission.AndPermissionUtils;
import com.ky.manage.ui.SignatureView;
import com.ky.manage.utils.FileUtil;
import com.ky.manage.utils.TimeUtil;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.ZyUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import java.io.File;
import java.io.IOException;

import cz.msebera.android.httpclient.Header;

/**
 * 户内：整改、安检签名
 * 客户签名页
 */
public class ClientSignActivity extends BaseActivity {

    private SignatureView signatureView;
    private String mId = "";

    public static final int SIGN_INDOOR_SECURITY_CHECK = 1;
    public static final int SIGN_INDOOR_MEND = 2;
    private int mType = SIGN_INDOOR_SECURITY_CHECK;

    public static void toClientSignActivity(BaseActivity baseActivity, String id, int type) {
        Intent intent = new Intent(baseActivity, ClientSignActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("type", type);
        baseActivity.toActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_client_sign;
    }

    @Override
    protected void initView() {
        findView(R.id.back_iv, v -> {
            finish();
        });
        findTextView(R.id.page_title_tv, "检测记录-客户签字");
        signatureView = findView(R.id.signature_view);

        findView(R.id.reset_sign_tv, v -> {
            //重新签名
            if (signatureView.getSigstatus()) {
                signatureView.clear();
            }
        });
        findView(R.id.confirm_sign_tv, v -> {
            //确定签名
            if (signatureView.getSigstatus()) {
                AndPermissionUtils.getInstance().requestStoragePermissionGroup(this, () -> {
                    try {
                        ZyUtils.getInstance().showLoadingDialog(this, "");
                        String fileNameWithPath = FileUtil.createMkdirsFile(OverallData.sdkPath + "ky/",
                                TimeUtil.getDate(System.currentTimeMillis()) + "_sign.png");
                        boolean saveResult = signatureView.save( fileNameWithPath);
                        if (saveResult) {
                            uploadLoadImg(fileNameWithPath, url -> {
                                submitIndoorSignInfo(url);
                            });
                        } else {
                            ZyUtils.getInstance().hideLoadingDialog();
                            ToastUtils.showRoundRectToast("提交失败");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        ZyUtils.getInstance().hideLoadingDialog();
                    }
                });
            }
        });
    }
    /**
     * 图片上传
     * @param imgPath
     * @param uploadAllImgCallback
     */
    private void uploadLoadImg(String imgPath, UploadAllImgCallback uploadAllImgCallback) {
        ZyUtils.getInstance().insertLog("uploadLoadImg", "imgPath = " + imgPath);
        BusinessHttpReqUtils.getInstance().uploadFile(new File(imgPath), new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("uploadLoadImg", "onFailure statusCode = " + statusCode
                        + ", responseString = " + responseString);
                ToastUtils.showRoundRectToast("上传文件失败：" + responseString);
                ZyUtils.getInstance().hideLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                ZyUtils.getInstance().insertLog("uploadLoadImg", "onSuccess statusCode = " + statusCode
                        + ", response = " + responseString);
                UploadFileInfoResp fileInfoResp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, UploadFileInfoResp.class);
                Log.d("lhm", "sign uploadLoadImg resp= " + responseString);
                if (null != fileInfoResp && fileInfoResp.code == 200) {
                    //上传成功
                    String url = fileInfoResp.url.replace("\\", "");
                    if (null != uploadAllImgCallback) {
                        uploadAllImgCallback.onUploadSuccess(url);
                    }
                } else {
                    ToastUtils.showRoundRectToast("上传文件失败");
                    ZyUtils.getInstance().hideLoadingDialog();
                }
            }
        });
    }

    public interface UploadAllImgCallback {
        void onUploadSuccess(String url);
    }

    /**
     * 提交
     * @param signImgUrl
     */
    private void submitIndoorSignInfo(String signImgUrl) {
        String url = BusinessHttpReqUtils.SERVICE_DOMAIN;
        RequestParams requestParams = new RequestParams();
        String action = "";
        try {
            if (mType == SIGN_INDOOR_SECURITY_CHECK) {
                action = "/appApi/submitIndoor";
                requestParams.put("indoorId", Long.parseLong(mId));
                requestParams.put("signPic", signImgUrl);
                url = url + action + "?indoorId=" + Long.parseLong(mId) + "&signPic=" + signImgUrl;

            } else if (mType == SIGN_INDOOR_MEND) {
                action = "/appApi/submitIndoorMend";
                requestParams.put("recordId", Integer.parseInt(mId));
                requestParams.put("signPic", signImgUrl);
                url = url + action + "?recordId=" + Long.parseLong(mId) + "&signPic=" + signImgUrl;

            }
        } catch (Exception e) {
            Log.d("submitIndoorSignInfo", "e = " + e.toString());
        }
        Log.d("lhm", "url=" + url);
        AsyncHttpUtils.getInstance().post(url, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("submitIndoorSignInfo", "onFailure statusCode = "
                        + statusCode + ", responseString = " + responseString);
                Log.d("lhm", "submitIndoorSignInfo  onFailure = " + responseString);
                ToastUtils.showRoundRectToast("服务器异常，请稍候重试");
                ZyUtils.getInstance().hideLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                ZyUtils.getInstance().insertLog("submitIndoorSignInfo", "onSuccess statusCode = "
                        + statusCode + ", responseString = " + responseString);
                Log.d("lhm", "submitIndoorSignInfo  onSuccess = " + responseString);
                ZyUtils.getInstance().hideLoadingDialog();
                if (statusCode == 200) {
                    ToastUtils.showRoundRectToast("提交成功");
                    finish();
                } else {
                    ToastUtils.showRoundRectToast("服务器异常，请稍候重试");
                }
            }
        });
    }

    @Override
    protected void initData() {
        mId = getIntent().getStringExtra("id");
        mType = getIntent().getIntExtra("type", SIGN_INDOOR_SECURITY_CHECK);
    }
}